<template>
  <div class="news-detail">
    <el-card class="news-card">
      <template #header>
        <div class="news-header">
          <h1 class="news-title">{{ news.title }}</h1>
          <div class="news-meta">
            <span class="reporter">记者：{{ news.reporter }}</span>
            <span class="publish-time">发布时间：{{ formatDate(news.publish_time) }}</span>
            <span class="views">阅读：{{ news.read_count }}</span>
          </div>
        </div>
      </template>
      
      <div class="news-content">{{ news.content }}</div>
      
      <div class="news-actions">
        <el-button 
          type="primary" 
          :icon="news.is_liked ? 'Star' : 'StarFilled'"
          @click="handleLikeNews"
          :loading="likeLoading"
          :disabled="!isLoggedIn"
        >
          {{ news.is_liked ? '取消点赞' : '点赞' }} ({{ news.like_count || 0 }})
        </el-button>
        <el-button type="success" :icon="Share" @click="handleShare">
          分享
        </el-button>
      </div>
    </el-card>

    <!-- 评论区 -->
    <el-card class="comments-card">
      <template #header>
        <div class="comments-header">
          <h2>评论区</h2>
          <span class="comment-count">共 {{ comments.length }} 条评论</span>
        </div>
      </template>

      <!-- 评论表单 -->
      <div v-if="isLoggedIn" class="comment-form">
        <el-input
          v-model="newComment"
          type="textarea"
          :rows="3"
          placeholder="写下你的评论..."
          :maxlength="500"
          show-word-limit
          :disabled="!isLoggedIn"
        />
        <div class="comment-form-actions">
          <el-button type="primary" @click="submitComment" :loading="commentLoading" :disabled="!isLoggedIn">
            发表评论
          </el-button>
        </div>
      </div>
      <div v-else class="login-tip">
        <el-alert
          title="请先登录后再发表评论"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <el-button type="primary" link @click="$router.push('/login')">
              去登录
            </el-button>
          </template>
        </el-alert>
      </div>

      <!-- 评论列表 -->
      <div class="comments-list">
        <div v-if="comments.length === 0" class="no-comments">
          暂无评论，快来发表第一条评论吧！
        </div>
        <div v-else v-for="comment in comments" :key="comment.comment_id" class="comment-item">
          <div class="comment-header">
            <el-avatar :size="32" class="user-avatar">
              {{ comment.username?.charAt(0).toUpperCase() }}
            </el-avatar>
            <div class="comment-info">
              <span class="username">{{ comment.username }}</span>
              <span class="time">{{ formatDate(comment.created_at) }}</span>
            </div>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
          <div class="comment-actions">
            <el-button 
              type="text" 
              size="small" 
              @click="handleCommentLike(comment)"
              :disabled="!isLoggedIn"
            >
              <el-icon>
                <component :is="comment.is_liked ? 'StarFilled' : 'Star'" />
              </el-icon>
              {{ comment.is_liked ? '取消点赞' : '点赞' }} ({{ comment.likes || 0 }})
            </el-button>
            <el-button 
              v-if="isLoggedIn && (comment.user_id === currentUser?.id || currentUser?.role === 'admin')"
              type="text" 
              size="small" 
              class="delete-btn"
              @click="handleDeleteComment(comment)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Star, StarFilled, Share, Delete } from '@element-plus/icons-vue'
import axios from '../config/axios'
import emitter from '../utils/eventBus'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const news = ref({})
const comments = ref([])
const newComment = ref('')
const commentLoading = ref(false)
const likeLoading = ref(false)
const isLoggedIn = ref(false)
const currentUserId = ref(null)
const currentUser = ref(null)

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 检查登录状态
const checkLoginStatus = async () => {
  const token = localStorage.getItem('token')
  if (token) {
    try {
      console.log('Checking login status with token:', token)
      const response = await axios.get('/api/auth/current-user', {
        headers: {
          Authorization: `Bearer ${token}`
        }
      })
      console.log('Login status response:', response.data)
      if (response.data.success) {
        isLoggedIn.value = true
        currentUserId.value = response.data.user.id
        currentUser.value = response.data.user
        console.log('User is logged in:', { isLoggedIn: isLoggedIn.value, userId: currentUserId.value })
      } else {
        console.log('Login check failed:', response.data.message)
        localStorage.removeItem('token')
        isLoggedIn.value = false
        currentUserId.value = null
        currentUser.value = null
      }
    } catch (error) {
      console.error('Failed to get user info:', error)
      if (error.response?.status === 401 || error.response?.status === 404) {
        localStorage.removeItem('token')
        isLoggedIn.value = false
        currentUserId.value = null
        currentUser.value = null
      }
    }
  } else {
    console.log('No token found in localStorage')
    isLoggedIn.value = false
    currentUserId.value = null
    currentUser.value = null
  }
}

// 获取新闻详情
const fetchNewsDetail = async () => {
  try {
    const response = await axios.get(`/api/news/${route.params.id}`)
    if (response.data.success) {
      news.value = response.data.data
    }
  } catch (error) {
    console.error('Failed to fetch news:', error)
    ElMessage.error('获取新闻详情失败')
  }
}

// 获取评论列表
const fetchComments = async () => {
  if (!route.params.id) {
    console.error('News ID is missing')
    return
  }

  try {
    const response = await axios.get(`/api/comments/news/${route.params.id}`)
    console.log('Fetched comments:', response.data)
    if (response.data.success) {
      // 为每个评论添加点赞状态
      comments.value = response.data.data.map(comment => ({
        ...comment,
        is_liked: false, // 默认未点赞
        likes: comment.likes || 0
      }))
    }
  } catch (error) {
    console.error('Failed to fetch comments:', error)
    ElMessage.error('获取评论失败')
  }
}

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  if (!route.params.id) {
    ElMessage.error('新闻ID不存在')
    return
  }

  try {
    commentLoading.value = true
    const commentData = {
      newsId: parseInt(route.params.id),
      content: newComment.value.trim()
    }
    
    console.log('Submitting comment with data:', commentData)
    
    const response = await axios.post('/api/comments', commentData)
    console.log('Comment submission response:', response.data)

    if (response.data.success) {
      ElMessage.success('评论发表成功')
      newComment.value = '' // 清空评论框
      await fetchComments() // 重新获取评论列表
    }
  } catch (error) {
    console.error('Submit comment error:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('评论发表失败')
    }
  } finally {
    commentLoading.value = false
  }
}

// 删除评论
const handleDeleteComment = async (comment) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    const result = await ElMessageBox.confirm(
      '确定要删除这条评论吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (result === 'confirm') {
      console.log('Deleting comment:', {
        commentId: comment.comment_id,
        newsId: route.params.id
      })
      
      const response = await axios.delete(`/api/comments/${comment.comment_id}`)
      console.log('Delete response:', response.data)
      
      if (response.data.success) {
        ElMessage.success('评论删除成功')
        await fetchComments() // 重新获取评论列表
      }
    }
  } catch (error) {
    if (error === 'cancel') {
      return
    }
    console.error('Delete comment error:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('删除评论失败')
    }
  }
}

// 点赞评论
const handleCommentLike = async (comment) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再点赞')
    return
  }

  try {
    console.log('Liking comment:', comment)
    const response = await axios.post(`/api/comments/${comment.comment_id}/like`, {
      user_id: currentUser.value.id
    })
    console.log('Comment like response:', response.data)

    if (response.data.success) {
      // 更新评论的点赞状态和数量
      comment.is_liked = !comment.is_liked
      if (comment.is_liked) {
        comment.likes = (comment.likes || 0) + 1
        ElMessage.success('点赞成功')
      } else {
        comment.likes = Math.max((comment.likes || 0) - 1, 0)
        ElMessage.success('已取消点赞')
      }
    }
  } catch (error) {
    console.error('Like comment error:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('点赞失败')
    }
  }
}

// 点赞新闻
const handleLikeNews = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再点赞')
    return
  }

  try {
    likeLoading.value = true
    console.log('Current user:', currentUser.value)
    
    const response = await axios.post(`/api/likes/news/${route.params.id}/like`, {
      user_id: currentUser.value.id
    })
    console.log('Like response:', response.data)

    if (response.data.success) {
      // 更新新闻的点赞状态和数量
      news.value.is_liked = response.data.liked
      if (response.data.liked) {
        news.value.like_count = (news.value.like_count || 0) + 1
        ElMessage.success('点赞成功')
      } else {
        news.value.like_count = Math.max((news.value.like_count || 0) - 1, 0)
        ElMessage.success('已取消点赞')
      }
    }
  } catch (error) {
    console.error('Like news error:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('操作失败')
    }
  } finally {
    likeLoading.value = false
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 分享新闻
const handleShare = () => {
  const url = window.location.href
  if (navigator.share) {
    navigator.share({
      title: news.value.title,
      url: url
    }).catch(console.error)
  } else {
    navigator.clipboard.writeText(url)
    ElMessage.success('链接已复制到剪贴板')
  }
}

// 监听登录状态变化
const handleLoginStatusChange = (data) => {
  isLoggedIn.value = data.isLoggedIn
  currentUserId.value = data.user?.id
  currentUser.value = data.user
}

onMounted(async () => {
  console.log('Component mounted, news ID:', route.params.id)
  await checkLoginStatus()
  if (isLoggedIn.value) {
    console.log('User is logged in:', currentUser.value)
  }
  await fetchNewsDetail()
  await fetchComments()
  emitter.on('loginStatusChanged', handleLoginStatusChange)
})

onUnmounted(() => {
  emitter.off('loginStatusChanged', handleLoginStatusChange)
})
</script>

<style scoped>
.news-detail {
  max-width: 800px;
  margin: 80px auto 20px;
  padding: 0 20px;
}

.news-card {
  margin-bottom: 20px;
}

.news-header {
  text-align: center;
}

.news-title {
  margin: 0 0 20px;
  font-size: 24px;
  color: #303133;
}

.news-meta {
  display: flex;
  justify-content: center;
  gap: 20px;
  color: #909399;
  font-size: 14px;
}

.news-content {
  white-space: pre-wrap;
  line-height: 1.8;
  color: #606266;
  margin: 20px 0;
}

.news-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.comments-card {
  margin-top: 20px;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comments-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.comment-count {
  color: #909399;
  font-size: 14px;
}

.comment-form {
  margin-bottom: 20px;
}

.comment-form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.login-tip {
  margin-bottom: 20px;
}

.comments-list {
  margin-top: 20px;
}

.no-comments {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.comment-item {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-avatar {
  background-color: #409EFF;
  color: #fff;
  font-weight: bold;
  margin-right: 10px;
}

.comment-info {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 500;
  color: #303133;
}

.time {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.comment-content {
  color: #606266;
  line-height: 1.6;
  margin: 10px 0;
}

.comment-actions {
  display: flex;
  gap: 15px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}
</style> 